/*
 * AgendaNotePanel.java
 *
 * Created on 15 mars 2008, 15:15
 */

package sheep.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTarget;
import org.jdesktop.swingx.JXPanel;

import sheep.controller.Workspace;
import sheep.model.Worker;
import sheep.view.Component.UserTableModel;
import sheep.view.Component.ActionButton;
import sheep.view.Component.RoundedPanel;
import sheep.view.graphics2d.AnimationUtil;
import javax.swing.filechooser.*;

import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.JXTable;
import sheep.model.WorkGroup;
import sheep.view.Component.GroupTableModel;
import sheep.view.Component.ImageChooser.ImageFilter;
import sheep.view.Component.ImageChooser.ImagePreview;

/**
 *
 * @author  geek
 */
public class WorkGroupEditPanel extends JXPanel {
  
  private JXPanel MainPanel;
  private javax.swing.JPanel centerPanel;
  private javax.swing.JButton cornerQuitBttn;
  private javax.swing.JPanel northPanel;
  private javax.swing.JButton quitBttn;
  private javax.swing.JPanel southPanel;
  private javax.swing.JButton validBttn;
  private javax.swing.JButton btnPhoto;
  private JList addedUsersTable;
  private javax.swing.JScrollPane addedUsersTableScrollPane;
  private javax.swing.JButton btnAjouter;
  private javax.swing.JButton btnSupprimer;
  private javax.swing.JPanel contentPanel;
  private javax.swing.JPanel fieldsPanel;
  private javax.swing.JLabel lblNom;
  private javax.swing.JLabel lblPhoto;
  private javax.swing.JPanel mainPanel;
  private javax.swing.JTextField txtNom;
  private javax.swing.JTextField txtPhoto;
  private javax.swing.JPanel usersPanel;
  private JList usersTable;
  private DefaultListModel usersTableModel;
  private DefaultListModel addedUsersTableModel;
  private javax.swing.JScrollPane usersTableScrollPane;
  private java.awt.Font panelFont = new Font("Trebuchet MS-Plain-13", Font.BOLD, 12);
  private LinkedList<Worker> workers = new LinkedList<Worker>();
  private Workspace workSpace;
  private WorkGroup workGroup;
  private JTable table;
  private GroupTableModel model;
  Object usersHeaders[] = { "Numéro", "Prénom", "Nom", "Job" };  
  
  private static int photoHeight=100, photoWidth=100;
  
  public void setWorkGroup(WorkGroup w) { 
    this.workGroup = w;
  }
  
  public int getIdFromElement(Object element) {
    String[] result = element.toString().split(":", 2);
    String[] result2 = result[0].split("#", 2);
    
    return Integer.valueOf(result2[1]);
  }
  
  private void setUsersList() {
    usersTableModel.removeAllElements();
    for(Worker w : workSpace.getWorkersList()) {
      if(workGroup!=null && !workGroup.hasWorker(w))
        usersTableModel.addElement("#" + w.getId() + ": " + w.getFirstName() + " " + w.getLastName());
      else if(workGroup == null)
        usersTableModel.addElement("#" + w.getId() + ": " + w.getFirstName() + " " + w.getLastName());
    }
  }
  
  public void setFieldsValues() {
    txtNom.setText("");
    txtPhoto.setText("");
    addedUsersTableModel.removeAllElements();
    usersTableModel.removeAllElements();
    workers = new LinkedList<Worker>();
    
    if(workGroup==null || workGroup.getWorkersList().size() == 0) {
      addedUsersTableModel.addElement("   ");
    }
    usersTableModel.addElement("     ");
    
    setUsersList();
    if(this.workGroup != null) {
      txtNom.setText(workGroup.getName());
      txtPhoto.setText(workGroup.getPictureURL());
      
      if(workGroup.getWorkersList().size() > 0) {
        addedUsersTableModel.removeAllElements();
        for(Worker w : workGroup.getWorkersList()) {
         addedUsersTableModel.addElement("#" + w.getId() + ": " + w.getFirstName() + " " + w.getLastName());
         workers.add(w);
        }
      }
    }
  }
  
  public WorkGroupEditPanel(Workspace workSpace, WorkGroup w, JTable table, GroupTableModel model) {
    this.workSpace = workSpace;
    this.workGroup = w;
    this.table = table;
    this.model = model;
    initComponents();
  }
  
  private void initComponents() {
    
    java.awt.GridBagConstraints gridBagConstraints;

    fieldsPanel = new javax.swing.JPanel();
    lblNom = new javax.swing.JLabel();
    txtNom = new javax.swing.JTextField();
    lblPhoto = new javax.swing.JLabel();
    txtPhoto = new javax.swing.JTextField();
    usersPanel = new javax.swing.JPanel();
    usersPanel.setOpaque(false);
    usersTableScrollPane = new javax.swing.JScrollPane();
    usersTable = new JXList();
    addedUsersTableScrollPane = new javax.swing.JScrollPane();
    addedUsersTable = new JXList();
    btnAjouter = new ActionButton();
    btnSupprimer = new ActionButton();
    btnPhoto = new ActionButton("Choisir...");
    
    MainPanel = new JXPanel();
    centerPanel = new javax.swing.JPanel();  
   
    northPanel = new javax.swing.JPanel();
    
    javax.swing.JLabel mainTitleLabel = new javax.swing.JLabel();
    
    cornerQuitBttn = new javax.swing.JButton();
    southPanel = new javax.swing.JPanel();
    validBttn = new ActionButton();
    quitBttn = new ActionButton();

    setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 45, 10, 45));
    setOpaque(false);
    setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));

    MainPanel.setBackground(new java.awt.Color(255, 255, 255));
    MainPanel.setMaximumSize(new java.awt.Dimension(2147483647, 300));
    MainPanel.setMinimumSize(new java.awt.Dimension(73, 200));
    MainPanel.setPreferredSize(new java.awt.Dimension(100, 200));
    MainPanel.setLayout(new java.awt.BorderLayout());

    centerPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 10, 1, 10));
    centerPanel.setOpaque(false);
    centerPanel.setLayout(new BorderLayout());
    
    fieldsPanel.setLayout(new java.awt.GridBagLayout());
    fieldsPanel.setOpaque(false);
    
    lblNom.setText("Nom : "); // NOI18N
    lblNom.setFont(panelFont);
    lblNom.setForeground(Color.WHITE);
    fieldsPanel.add(lblNom, new java.awt.GridBagConstraints());
    
    lblPhoto.setText("Photo : ");
    lblPhoto.setFont(panelFont);
    lblPhoto.setForeground(Color.WHITE);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    fieldsPanel.add(lblPhoto, gridBagConstraints);
    
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.weightx = 35.0;
    fieldsPanel.add(txtNom, gridBagConstraints);
    
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.weightx = 35.0;
    fieldsPanel.add(txtPhoto, gridBagConstraints);

    
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    fieldsPanel.add(btnPhoto, gridBagConstraints);
    btnPhoto.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        JFileChooser chooser = new JFileChooser();
        FileFilter filter = new ImageFilter();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileFilter(filter);
      //  chooser.setFileView(new ImageFileView());
        chooser.setAccessory(new ImagePreview(chooser));
        
        int returnVal = chooser.showOpenDialog(new JPanel());
        if(returnVal == JFileChooser.APPROVE_OPTION) {
          String fileChoosed;
          fileChoosed = chooser.getCurrentDirectory() + 
                System.getProperties().getProperty("file.separator") + 
                chooser.getSelectedFile().getName();
           
          txtPhoto.setText(fileChoosed);
        }
      }
    });
    
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    fieldsPanel.add(new JLabel("   "), gridBagConstraints);
    
    centerPanel.add(fieldsPanel, java.awt.BorderLayout.NORTH);
    
    
    usersPanel.setLayout(new java.awt.GridBagLayout());
    usersTableScrollPane.setViewportView(usersTable);
    usersTableModel = new DefaultListModel();
    usersTable.setModel(usersTableModel);
    
    JLabel lblParticipants = new JLabel("Participants: ");
    lblParticipants.setForeground(Color.WHITE);
    lblParticipants.setFont(panelFont);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    usersPanel.add(lblParticipants, gridBagConstraints);
    
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 100.0;
    gridBagConstraints.weighty = 100.0;
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    usersPanel.add(usersTableScrollPane, gridBagConstraints);
    
    addedUsersTableScrollPane.setViewportView(addedUsersTable);
    addedUsersTableModel = new DefaultListModel();
    addedUsersTable.setModel(addedUsersTableModel);
    
    JLabel lblMembres = new JLabel("Membres du groupe: ");
    lblMembres.setForeground(Color.WHITE);
    lblMembres.setFont(panelFont);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    usersPanel.add(lblMembres, gridBagConstraints);
    
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.weightx = 100.0;
    gridBagConstraints.weighty = 100.0;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    usersPanel.add(addedUsersTableScrollPane, gridBagConstraints);

    btnAjouter.setText("  >>>  "); // NOI18N
    btnAjouter.setName("btnAjouter"); // NOI18N
    btnAjouter.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent arg0) {
        if(workGroup==null || workers.size()==0) {
          addedUsersTableModel.removeAllElements();
        }
        
        Object[] indexes = usersTable.getSelectedValues();
        
        for(Object o : indexes) {
          int nb = getIdFromElement(o);
          usersTableModel.removeElement(o);
          Worker w = workSpace.getWorker(nb);
          workers.add(w);
          addedUsersTableModel.addElement("#" + w.getId() + ": " + w.getFirstName() + " " + w.getLastName());
        }
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 1;
    usersPanel.add(btnAjouter, gridBagConstraints);
    
    btnSupprimer.setText("  <<<  "); // NOI18N
    btnSupprimer.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent arg0) {
        
        Object[] indexes = addedUsersTable.getSelectedValues();
        
        for(Object o : indexes) {
          int nb = getIdFromElement(o);
          addedUsersTableModel.removeElement(o);
          Worker w = workSpace.getWorkerFromId(nb);
          workers.remove(w);
          usersTableModel.addElement("#" + w.getId() + ": " + w.getFirstName() + " " + w.getLastName());
        }
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 2;
    usersPanel.add(btnSupprimer, gridBagConstraints);
    
    centerPanel.add(usersPanel, java.awt.BorderLayout.CENTER);

  //  centerPanel.add(contentPanel, java.awt.BorderLayout.CENTER);
    

 /*   btnPhoto.setText("Choisir..."); // NOI18N
    btnPhoto.setName("jButton1"); // NOI18N
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 2;
    centerPanel.add(btnPhoto, gridBagConstraints);
    btnPhoto.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        JFileChooser chooser = new JFileChooser();
        FileFilter filter = new ImageFilter();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileFilter(filter);
      //  chooser.setFileView(new ImageFileView());
        chooser.setAccessory(new ImagePreview(chooser));
        
        int returnVal = chooser.showOpenDialog(new JPanel());
        if(returnVal == JFileChooser.APPROVE_OPTION) {
          String fileChoosed;
          fileChoosed = chooser.getCurrentDirectory() + 
                System.getProperties().getProperty("file.separator") + 
                chooser.getSelectedFile().getName();
           
          txtPhoto.setText(fileChoosed);
        }
      }
    });
*/
    
    ///////////////////////////////
    //DESSIN PRINCIPALE
    /////////////////////////////////////////////////////////////
    
    MainPanel.add(centerPanel, java.awt.BorderLayout.CENTER);

    northPanel.setOpaque(false);
    northPanel.setLayout(new java.awt.BorderLayout());
    northPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 15, 10));
    mainTitleLabel.setFont(new java.awt.Font("Tahoma", 1, 20));
    mainTitleLabel.setForeground(new java.awt.Color(255, 255, 255));
    mainTitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    mainTitleLabel.setText("Informations sur le groupe");
    northPanel.add(mainTitleLabel, java.awt.BorderLayout.CENTER);

    cornerQuitBttn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/button-close.png"))); // NOI18N
    cornerQuitBttn.setToolTipText("Close editor");
    cornerQuitBttn.setBorder(null);
    cornerQuitBttn.setBorderPainted(false);
    cornerQuitBttn.setContentAreaFilled(false);
    cornerQuitBttn.setFocusPainted(false);
    cornerQuitBttn.setFocusable(false);
    cornerQuitBttn.setMargin(new java.awt.Insets(0, 0, 0, 0));
    cornerQuitBttn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/button-close-pressed.png"))); // NOI18N
    cornerQuitBttn.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/button-close-over.png"))); // NOI18N
    cornerQuitBttn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cornerQuitBttnActionPerformed(evt);
      }
    });
    northPanel.add(cornerQuitBttn, java.awt.BorderLayout.EAST);

    MainPanel.add(northPanel, java.awt.BorderLayout.PAGE_START);

    //southPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 1, 0, 1));
    southPanel.setOpaque(false);
    southPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 15, 5));

    validBttn.setText("   Ok    ");
    southPanel.add(validBttn);
    validBttn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        OKBttnActionPerformed(evt);
      }
    });
    
    quitBttn.setText("Annuler");
    quitBttn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        quitBttnActionPerformed(evt);
      }
    });
    southPanel.add(quitBttn);

    MainPanel.add(southPanel, java.awt.BorderLayout.PAGE_END);
    MainPanel.setOpaque(true);
    MainPanel.setBackgroundPainter(new sheep.view.utils.swingx.PainterBlackCustom());
    add(new RoundedPanel(MainPanel));
  }// </editor-fold>

  private void cornerQuitBttnActionPerformed(java.awt.event.ActionEvent evt) {
    final Container parent = this.getParent();
    Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
    fadeOut.addTarget(new TimingTarget() {
      @Override
      public void begin() {}
      @Override
      public void end() {
        setVisible2(false);
        parent.repaint();
      }
      @Override
      public void timingEvent(float f) {}
      @Override
      public void repeat() {}
    });
    fadeOut.start();
}

  private void quitBttnActionPerformed(java.awt.event.ActionEvent evt) {
        final Container parent = this.getParent();
    Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
    fadeOut.addTarget(new TimingTarget() {
      @Override
      public void begin() {}
      @Override
      public void end() {
        setVisible2(false);
        parent.repaint();
      }
      @Override
      public void timingEvent(float f) {}
      @Override
      public void repeat() {}
    });
    fadeOut.start();
  }
 
    private void OKBttnActionPerformed(java.awt.event.ActionEvent evt) {
        final Container parent = this.getParent();
    Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
    fadeOut.addTarget(new TimingTarget() {
      @Override
      public void begin() {
        if(workGroup!=null) {
          workGroup.setName(txtNom.getText());
          workGroup.setPictureURL(txtPhoto.getText());
        }
        else {
          workGroup = new WorkGroup(txtNom.getText(), txtPhoto.getText());
          workSpace.getWorkGroupsList().add(workGroup);
        }
        
        Comparator c = new Comparator() {

          public int compare(Object o, Object o2) {
            if( ((Worker)o).getId() < ((Worker)o).getId() )
              return -1;
            else if( ((Worker)o).getId() == ((Worker)o).getId() )
              return 0;
            else
              return 1;
          }
          
        };
        
        Collections.sort(workers, c);
        
        workGroup.clearWorkers();
        for(Worker w : workers)
          workGroup.addWorker(w);
      }
      @Override
      public void end() {
        model.setData(workSpace.getWorkGroupsList());
        table.setModel(model);
        table.repaint();
        setVisible2(false);
        parent.repaint();
      }
      @Override
      public void timingEvent(float f) {}
      @Override
      public void repeat() {}
    });
    fadeOut.start();
  }
    
    void setVisible2 (boolean aFlag){
    super.setVisible(aFlag);
    setEnabled(aFlag);
    setFocusable(aFlag);
    if (aFlag){
      ///////////////////////////
      //INIT
      ///////////////////////////
    }
  }


  @Override
  public void setVisible(final boolean aFlag) {
    final Container parent = this.getParent();   
    if (!aFlag){ 
      Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
      fadeOut.addTarget(new TimingTarget() {
        @Override
        public void begin() {}
        @Override
        public void end() {
            setVisible2(false);
            parent.repaint();            
        }
        @Override
        public void timingEvent(float f) {}
        @Override
        public void repeat() {}
      });
      fadeOut.start();
    }else{
        Animator fadeIn = AnimationUtil.createFadeInAnimation(this);
        fadeIn.addTarget(new TimingTarget() {
        @Override
        public void begin() {setVisible2(true);}
        @Override
        public void end() {
          parent.repaint();
        }
        @Override
        public void timingEvent(float f) {}
        @Override
        public void repeat() {}
      });
      fadeIn.start();   
    }
  }
}



